package com.lezhi.socialgram.service.sys.impl;

import com.lezhi.socialgram.enums.ResultEnum;
import com.lezhi.socialgram.exception.SocialGramException;
import com.lezhi.socialgram.mapper.sys.PasswordMapper;
import com.lezhi.socialgram.model.sys.UpdatePwdUser;
import com.lezhi.socialgram.service.sys.PasswordService;
import com.lezhi.socialgram.util.Param;
import com.lezhi.socialgram.util.Result;
import com.lezhi.socialgram.util.ResultUtils;
import com.lezhi.socialgram.util.XUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * Created by daizhen on 2017/3/30.
 */
@Service
public class PasswordServiceImpl implements PasswordService {

    private static final Logger logger = LoggerFactory.getLogger(PasswordServiceImpl.class);

    @Autowired
    PasswordMapper passwordMapper;

    @Override
    public Result updatePassword(UpdatePwdUser updatePwdUser) {
        try {
            String indexById = XUtil.getTableNameIndexById(updatePwdUser.getUserId());
            updatePwdUser.setTable(Param.T_USER_TABLE_PREFIX + indexById);
//            Long id = passwordMapper.findByPassword(updatePwdUser);
//            if (id == null)
//                return ResultUtils.error(ResultEnum.AUTH_FAILED);
            String p = DigestUtils.md5DigestAsHex(updatePwdUser.getNewPwd().getBytes());
            updatePwdUser.setNewPwd(DigestUtils.md5DigestAsHex((updatePwdUser.getUserId() + p).getBytes()));
            passwordMapper.updatePassword(updatePwdUser);
            return ResultUtils.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }
}
